import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../l10n/app_localizations.dart';
import '../providers/auth_provider.dart';
import '../utils/language_manager.dart';
import '../utils/theme_manager.dart';
import '../theme/app_colors.dart';

class SettingsPage extends StatefulWidget {
  const SettingsPage({super.key});

  @override
  State<SettingsPage> createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  int _clickCount = 0;

  @override
  void initState() {
    super.initState();
    // 移除了代理设置加载逻辑
  }

  @override
  void dispose() {
    // 移除了代理设置控制器释放逻辑
    super.dispose();
  }

  // 移除了代理设置相关方法

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context)!;
    final screenWidth = MediaQuery.of(context).size.width;
    final isSmallScreen = screenWidth < 600;
    
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      body: Padding(
        padding: EdgeInsets.all(isSmallScreen ? 16 : 24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 页面标题
            GestureDetector(
              onTap: _onTitleTap,
              child: Text(
                localizations.settings,
                style: TextStyle(
                  color: Theme.of(context).textTheme.titleLarge?.color,
                  fontSize: isSmallScreen ? 20 : 24,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            SizedBox(height: isSmallScreen ? 20 : 32),
            
            // 设置项列表
            Expanded(
              child: ListView(
                children: [
                  // 主题设置
                  _buildSettingsSection(
                    context,
                    localizations.theme,
                    Icons.brightness_6,
                    isSmallScreen,
                    child: Consumer<ThemeManager>(
                      builder: (context, themeManager, child) {
                        return Column(
                          children: [
                            _buildThemeOption(
                              context,
                              localizations.darkMode,
                              ThemeManager.darkTheme,
                              themeManager.isDarkMode,
                              themeManager,
                              isSmallScreen,
                            ),
                            SizedBox(height: isSmallScreen ? 8 : 12),
                            _buildThemeOption(
                              context,
                              localizations.lightMode,
                              ThemeManager.lightTheme,
                              themeManager.isLightMode,
                              themeManager,
                              isSmallScreen,
                            ),
                          ],
                        );
                      },
                    ),
                  ),
                  
                  SizedBox(height: isSmallScreen ? 16 : 24),
                  
                  // 语言设置
                  _buildSettingsSection(
                    context,
                    localizations.language,
                    Icons.language,
                    isSmallScreen,
                    child: Consumer<LanguageManager>(
                      builder: (context, languageManager, child) {
                        return Column(
                          children: [
                            _buildLanguageOption(
                              context,
                              AppLocalizations.of(context)!.chinese,
                              'zh',
                              languageManager.isChinese,
                              languageManager,
                              isSmallScreen,
                            ),
                            SizedBox(height: isSmallScreen ? 8 : 12),
                            _buildLanguageOption(
                              context,
                              AppLocalizations.of(context)!.english,
                              'en',
                              languageManager.isEnglish,
                              languageManager,
                              isSmallScreen,
                            ),
                          ],
                        );
                      },
                    ),
                  ),
                  
                  SizedBox(height: isSmallScreen ? 16 : 24),
                  
                  // 软件更新
                  _buildSettingsSection(
                    context,
                    AppLocalizations.of(context)!.softwareUpdate,
                    Icons.system_update,
                    isSmallScreen,
                    child: _buildUpdateSection(context, isSmallScreen),
                  ),
                  
                  SizedBox(height: isSmallScreen ? 16 : 24),
                  
                  // 退出选项
                  Center(
                    child: Container(
                      width: 220,
                      decoration: BoxDecoration(
                        color: Theme.of(context).cardColor,
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: AppColors.of(context).error,
                          width: 1,
                        ),
                      ),
                      child: InkWell(
                        onTap: () => _showLogoutDialog(context),
                        borderRadius: BorderRadius.circular(12),
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: isSmallScreen ? 12 : 16),
                          child: Center(
                            child: Text(
                              AppLocalizations.of(context)!.logout,
                              style: TextStyle(
                                color: AppColors.of(context).error,
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSettingsSection(
    BuildContext context,
    String title,
    IconData icon,
    bool isSmallScreen, {
    required Widget child,
  }) {
    return Container(
      padding: EdgeInsets.all(isSmallScreen ? 16 : 20),
      decoration: BoxDecoration(
        color: Theme.of(context).cardColor,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: Theme.of(context).dividerColor,
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                icon,
                color: AppColors.of(context).primary,
                size: isSmallScreen ? 20 : 24,
              ),
              SizedBox(width: isSmallScreen ? 8 : 12),
              Text(
                title,
                style: TextStyle(
                  color: Theme.of(context).textTheme.titleLarge?.color,
                  fontSize: isSmallScreen ? 16 : 18,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
          SizedBox(height: isSmallScreen ? 12 : 16),
          child,
        ],
      ),
    );
  }

  Widget _buildThemeOption(
    BuildContext context,
    String title,
    String themeValue,
    bool isSelected,
    ThemeManager themeManager,
    bool isSmallScreen,
  ) {
    return InkWell(
      onTap: () {
        themeManager.setTheme(themeValue);
      },
      borderRadius: BorderRadius.circular(8),
      child: Container(
        padding: EdgeInsets.symmetric(
          horizontal: isSmallScreen ? 12 : 16,
          vertical: isSmallScreen ? 10 : 12,
        ),
        decoration: BoxDecoration(
          color: isSelected ? AppColors.of(context).primary.withValues(alpha: 0.1) : Colors.transparent,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: isSelected ? AppColors.of(context).primary : Theme.of(context).dividerColor,
            width: 1,
          ),
        ),
        child: Row(
          children: [
            Icon(
              isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
              color: isSelected ? AppColors.of(context).primary : AppColors.of(context).onSurface.withValues(alpha: 0.6),
              size: isSmallScreen ? 18 : 20,
            ),
            SizedBox(width: isSmallScreen ? 8 : 12),
            Text(
              title,
              style: TextStyle(
                color: isSelected ? AppColors.of(context).primary : Theme.of(context).textTheme.bodyLarge?.color,
                fontSize: isSmallScreen ? 14 : 16,
                fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLanguageOption(
    BuildContext context,
    String title,
    String languageCode,
    bool isSelected,
    LanguageManager languageManager,
    bool isSmallScreen,
  ) {
    return InkWell(
      onTap: () {
        languageManager.setLanguage(languageCode);
      },
      borderRadius: BorderRadius.circular(8),
      child: Container(
        padding: EdgeInsets.symmetric(
          horizontal: isSmallScreen ? 12 : 16,
          vertical: isSmallScreen ? 10 : 12,
        ),
        decoration: BoxDecoration(
          color: isSelected ? AppColors.of(context).primary.withValues(alpha: 0.1) : Colors.transparent,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: isSelected ? AppColors.of(context).primary : Theme.of(context).dividerColor,
            width: 1,
          ),
        ),
        child: Row(
          children: [
            Icon(
              isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
              color: isSelected ? AppColors.of(context).primary : AppColors.of(context).onSurface.withValues(alpha: 0.6),
              size: isSmallScreen ? 18 : 20,
            ),
            SizedBox(width: isSmallScreen ? 8 : 12),
            Text(
              title,
              style: TextStyle(
                color: isSelected ? AppColors.of(context).primary : Theme.of(context).textTheme.bodyLarge?.color,
                fontSize: isSmallScreen ? 14 : 16,
                fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildUpdateSection(
    BuildContext context,
    bool isSmallScreen,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '${AppLocalizations.of(context)!.currentVersion}: 1.0.0',
          style: TextStyle(
            color: Theme.of(context).textTheme.bodyMedium?.color,
            fontSize: isSmallScreen ? 14 : 16,
          ),
        ),
        SizedBox(height: isSmallScreen ? 12 : 16),
        SizedBox(
          width: double.infinity,
          child: ElevatedButton(
            onPressed: () {
              _checkForUpdates(context);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.of(context).primary,
              foregroundColor: AppColors.of(context).onPrimary,
              padding: EdgeInsets.symmetric(
                vertical: isSmallScreen ? 12 : 16,
              ),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            child: Text(
              AppLocalizations.of(context)!.checkUpdate,
              style: TextStyle(
                fontSize: isSmallScreen ? 14 : 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      ],
    );
  }

  void _onTitleTap() {
    setState(() {
      _clickCount++;
    });
    
    if (_clickCount >= 3) {
      _clickCount = 0;
      _showPasswordDialog();
    }
  }

  void _showPasswordDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        String password = '';
        return AlertDialog(
          title: Text(AppLocalizations.of(context)!.enterPassword),
          content: TextField(
            obscureText: true,
            onChanged: (value) {
              password = value;
            },
            decoration: InputDecoration(
              hintText: AppLocalizations.of(context)!.enterPassword,
            ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text(AppLocalizations.of(context)!.cancel),
            ),
            TextButton(
              onPressed: () {
                if (password == '123456') {
                  // 密码正确，跳转到配置管理页面
                  Navigator.of(context).pop(); // 关闭密码对话框
                  // 跳转到配置管理页面（索引为3）
                  Navigator.of(context).pushNamed('/main', arguments: 3);
                } else {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text(AppLocalizations.of(context)!.passwordIncorrect)),
                  );
                }
              },
              child: Text(AppLocalizations.of(context)!.confirm),
            ),
          ],
        );
      },
    );
  }

  void _checkForUpdates(BuildContext context) {
    final localizations = AppLocalizations.of(context)!;
    // 模拟检查更新
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Theme.of(context).cardColor,
        title: Text(
          localizations.softwareUpdate,
          style: TextStyle(color: Theme.of(context).textTheme.titleLarge?.color),
        ),
        content: Text(
          localizations.currentLatestVersion,
          style: TextStyle(color: Theme.of(context).textTheme.bodyMedium?.color),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(
              localizations.confirm,
              style: const TextStyle(color: Colors.blue),
            ),
          ),
        ],
      ),
    );
  }

  void _showLogoutDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Theme.of(context).cardColor,
          title: Text(
            AppLocalizations.of(context)!.logoutConfirmTitle,
            style: TextStyle(color: Theme.of(context).textTheme.titleLarge?.color),
          ),
          content: Text(
            AppLocalizations.of(context)!.logoutConfirmMessage,
            style: TextStyle(color: Theme.of(context).textTheme.bodyMedium?.color),
          ),
          actions: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text(AppLocalizations.of(context)!.cancel),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    _performLogout(context);
                  },
                  child: Text(
                    AppLocalizations.of(context)!.logout,
                    style: const TextStyle(color: Colors.red),
                  ),
                ),
              ],
            ),
          ],
        );
      },
    );
  }

  void _performLogout(BuildContext context) async {
    try {
      final authProvider = Provider.of<AuthProvider>(context, listen: false);
      
      // 执行登出
      await authProvider.logout();
      
      // 导航到登录页面，使用 rootNavigator 确保能够导航
      if (!context.mounted) return;
      
      Navigator.of(context, rootNavigator: true).pushNamedAndRemoveUntil(
        '/login',
        (route) => false,
      );
    } catch (e) {
      // 如果登出失败，也尝试导航到登录页面
      debugPrint('Logout error: $e');
      if (!context.mounted) return;
      
      Navigator.of(context, rootNavigator: true).pushNamedAndRemoveUntil(
        '/login',
        (route) => false,
      );
    }
  }
}